<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { addApi, updateApi } from '@/api/api'

const title = ref('')
const open = ref(false)
const form = ref({
  id:'null',
  name:'',
  gender:'',
  username:'',
  phone:'',
  password:''
})

// 定义事件发射器
const emits = defineEmits(['list'])

const submitForm = async() => {
  let res;
  if(form.value.id && form.value.id !== 'null'){
    res = await updateApi(form.value)
  }else{ 
    res = await addApi(form.value)
  }
  if (res.code) { 
    ElMessage.success('操作成功')
    open.value = false
    // 确保触发刷新事件
    emits('list')
  }else { 
    ElMessage.error('操作失败')
  }
}

const rules = ref({
  name: [
    { required: true, message: "名称不能为空", trigger: "blur" }
  ],
  username: [
    { required: true, message: "员工编号不能为空", trigger: "blur" }
  ],
  gender: [
    { required: true, message: "性别不能为空", trigger: "blur" }
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" }
  ]
})

const cancel = () => {
  open.value = false
}

// 暴露属性和方法给父组件
defineExpose({
  title,
  open,
  form,
  cancel,
  submitForm 
})
</script>
<template>
  <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="projectRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="编号" prop="username">
          <el-input v-model="form.username" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
         <el-select v-model="form.gender" clearable placeholder="请选择" style="width: 240px">
         <el-option label="男" value="1" />
         <el-option label="女" value="2" />
        </el-select>
        </el-form-item>
         <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
</template>
<style scoped>
</style>